/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.servlet.member;

import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.dao.CategoryDAO;
import model.dao.PostDAO;
import model.dao.service.CategoryDAOService;
import model.dao.service.PostDAOService;
import model.entities.Category;
import model.entities.Post;
import model.entities.User;
import util.Constants;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import util.FileUpload;

/**
 *
 * @author Admin
 */
public class MemberPost extends HttpServlet {

    private final PostDAOService POST_SERVICE = PostDAO.getInstance();
    private final CategoryDAOService CATEGORY_SERVICE = CategoryDAO.getInstance();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = "";
        String title = null;
        String content = null;
        String imageName = "default.png";
        User currentUser;
        String categoryName = null;
        String editBy = null;
        String postID = null;
        ServletFileUpload fileUpload = new ServletFileUpload();
        try {
            FileItemIterator fit = fileUpload.getItemIterator(request);
            while (fit.hasNext()) {
                FileItemStream itemStream = fit.next();
                if (itemStream.isFormField()) {
                    String fileName = itemStream.getFieldName();
                    InputStream is = itemStream.openStream();
                    byte[] b = new byte[is.available()];
                    is.read(b);
                    String value = new String(b);
                    if (fileName.equals("postTitle")) {
                        title = value;
                    }
                    if (fileName.equals("postContent")) {
                        content = value;
                    }
                    if (fileName.equals("categoryName")) {
                        categoryName = value;
                    }
                    if (fileName.equals("action")) {
                        action = value;
                    }
                    if (fileName.equals("post_id")) {
                        postID = value;
                    }
                    if (fileName.equals("edit_by")) {
                        editBy = value;
                    }
                } else {

                    String path = getServletContext().getRealPath("/");
                    String filePath = path.replace("\\build\\web", "\\web\\img\\post");
                    String name = itemStream.getName();
                    StringTokenizer token = new StringTokenizer(name, ".");
                    String fileNameExtension = "";
                    while (token.hasMoreElements()) {
                        fileNameExtension = token.nextElement().toString();
                    }
                    int newPostID = POST_SERVICE.getNewPostID();
                    if (!fileNameExtension.equals("")) {
                        imageName = newPostID + "." + fileNameExtension;
                    }
                    FileUpload.processFile(filePath, itemStream, newPostID + "", fileNameExtension);
                }
            }
            Category cattegory = CATEGORY_SERVICE.getCategoryByName(categoryName);
            currentUser = (User) request.getSession().getAttribute(util.Constants.CURRENT_USER);
            int editID = 0;
            if (!postID.equals("")) {
                editID = Integer.valueOf(postID);
            } else {
                editID = POST_SERVICE.getNewPostID();
            }
            Post post = new Post(editID, title, content, imageName, getDatePost(), currentUser, cattegory, false);
            switch (action) {
                case "Publish":
                    publishPost(request, response, post, editBy);
                    break;
                case "Update":
                    updatePost(request, response, post, editBy, postID);
                    break;
            }

        } catch (Exception e) {
            System.err.println("doPost MemberPost error: " + e.toString());
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter(Constants.ACTION);
        try {
            switch (action) {
                case "newpost":
                    newPost(request, response);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updatePost(HttpServletRequest request, HttpServletResponse response, Post post, String editBy, String postID) throws Exception {
        post.setActive(true);
        boolean isSuccess = true;
        boolean isExit = POST_SERVICE.checkExitPost(post);
        if (!isExit) {
            isSuccess = POST_SERVICE.updatePost(post);
        }
        if (!isExit && isSuccess) {
            if (editBy.equals("admin")) {
                response.sendRedirect("/JudiBlog/postmanage");
            } else {
                response.sendRedirect("/JudiBlog/Page?p=home");
            }
        } else {
           
            if (!isExit && !isSuccess) {
                post.setPostID(-1);
                request.setAttribute(Constants.MSG_RESULT, "Update fail!");
            }
            if (isExit) {
                post.setPostID(-1);
                request.setAttribute(Constants.MSG_RESULT, "Post title has been exit!");
            }
            request.setAttribute(Constants.CURRENT_POST, post);
            request.setAttribute(Constants.PAGE, "newpost");
            if (editBy.equals("admin")) {
                request.setAttribute(Constants.EDIT_BY, "admin");
                request.getRequestDispatcher(util.Constants.URL_ADMIN).forward(request, response);
            } else {
                request.getRequestDispatcher(util.Constants.URL_MEMBER).forward(request, response);
            }
        }
    }

    private void publishPost(HttpServletRequest request, HttpServletResponse response, Post post, String editBy) throws Exception {
        post.setActive(true);
        boolean isSuccess = false;
        boolean isExit = POST_SERVICE.checkExitPost(post);
        if (!isExit) {
            isSuccess = POST_SERVICE.insertPost(post);
        }
        if (!isExit && isSuccess) {
            if (editBy.equals("admin")) {
                response.sendRedirect("/JudiBlog/postmanage");
            } else {
                response.sendRedirect("/JudiBlog/Page?p=home");
            }
        } else {
            if (!isExit && !isSuccess) {
                post.setPostID(-1);
                request.setAttribute(Constants.MSG_RESULT, "Publish fail!");
            }
            if (isExit) {
                post.setPostID(-1);
                request.setAttribute(Constants.MSG_RESULT, "Post title has been exit!");
            }
            request.setAttribute(Constants.CURRENT_POST, post);
            request.setAttribute(Constants.PAGE, "newpost");
            if (editBy.equals("admin")) {
                request.setAttribute(Constants.EDIT_BY, "admin");
                request.getRequestDispatcher(util.Constants.URL_ADMIN).forward(request, response);
            } else {
                request.getRequestDispatcher(util.Constants.URL_MEMBER).forward(request, response);
            }
        }
    }

//    private void savePost(HttpServletRequest request, HttpServletResponse response, Post post, String editBy) throws Exception {
//        post.setActive(true);
//        request.setAttribute(Constants.PAGE, "newpost");
//        if (!POST_SERVICE.checkExitPost(post)) {
//            if (POST_SERVICE.updatePost(post)) {
//                request.setAttribute(Constants.SAVE_RESULT, "success");
//                request.setAttribute(Constants.MSG_RESULT, "Save success");
//            } else {
//               
//                request.setAttribute(Constants.CURRENT_POST, post);
//                request.setAttribute(Constants.MSG_RESULT, "Save fail");
//            }
//        } else {
//            request.setAttribute(Constants.CURRENT_POST, post);
//            request.setAttribute(Constants.MSG_RESULT, "Post title has been exit!");
//        }
//        if (editBy.equals("admin")) {
//            request.setAttribute(Constants.EDIT_BY, "admin");
//            request.getRequestDispatcher(util.Constants.URL_ADMIN).forward(request, response);
//        } else {
//            request.getRequestDispatcher(util.Constants.URL_MEMBER).forward(request, response);
//        }
//    }

    private java.sql.Date getDatePost() {
        Date currentDate = new Date();
        return new java.sql.Date(currentDate.getTime());
    }

    private void newPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute(util.Constants.PAGE, "newpost");
        request.getRequestDispatcher(util.Constants.URL_MEMBER).forward(request, response);
    }
}
